package com.example.sharedpreferencesdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    EditText editFileName, editUserName, editAge;
    Button btnWrite, btnRead,btnDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editFileName = (EditText) findViewById(R.id.editFileName);
        editUserName = (EditText) findViewById(R.id.editUserName);
        editAge = (EditText) findViewById(R.id.editAge);
        btnWrite = (Button) findViewById(R.id.btnWrite);
        btnRead = (Button) findViewById(R.id.btnRead);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnWrite.setOnClickListener(this);
        btnRead.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String fileName = editFileName.getText().toString();
        String userName = editUserName.getText().toString();
        int age = Integer.parseInt(editAge.getText().toString());
        SharedPreferences sp = getSharedPreferences(fileName, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        switch (view.getId()) {
            case R.id.btnWrite:
                editor.putString("name", userName);
                editor.putInt("age", age);
                editor.commit();
                Toast.makeText(this,"已将数据存入data.xml中",Toast.LENGTH_LONG).show();
                break;
            case R.id.btnRead:
                userName="";
                age=0;
                userName=sp.getString("name","");
                age=sp.getInt("age",0);
                Toast.makeText(this,"读到的数据，姓名："+userName+",年龄:"+age, Toast.LENGTH_LONG).show();
                break;
            case R.id.btnDelete:
                editor.remove("name");
                editor.remove("age");
                editor.clear();
                editor.commit();
                Toast.makeText(this,"data.xml中的数据已全部删除！", Toast.LENGTH_LONG).show();
                break;
        }
    }
}
